import { reqLogin, reqGetUserInfo, reqGetUserDetailInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
export default {
  namespaced: true,
  state() {
    return {
      token: getToken() || '',
      userInfo: {}
    }
  },
  mutations: {
    setToken(state, newToken) {
      state.token = newToken
      setToken(newToken)
    },
    setUserInfo(state, newobj) {
      state.userInfo = newobj
    },
    removeToken(state) {
      state.token = ''
      removeToken()
    },
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    async login(context, loginForm) {
      const { data } = await reqLogin(loginForm)
      // console.log(data)
      context.commit('setToken', data)
    },
    async getUserInfo(context) {
      const { data: data1 } = await reqGetUserInfo()
      const { data: data2 } = await reqGetUserDetailInfo(data1.userId)
      // console.log('userInfo', data)
      // 合并对象
      // const res = { ...data1, ...data2 }
      const res = Object.assign({}, data1, data2)
      context.commit('setUserInfo', res)
      return res
    },
    logout({ commit }) {
      commit('removeToken')
      commit('removeUserInfo')
    }
  }
}
